<template>
  <div>
    <el-button @click="createPolygon">新建区域</el-button>
    <p>{{ cpath }}</p>
    <div class="app-container" id="app-container"></div>
  </div>
</template>

<script type="text/javascript">
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  data() {
    return {
      baseMap: {},
      mapPath: [[116.397428, 39.90923], [116.396427, 39.90823], [116.398429, 39.90823], [116.398429, 39.90923]],
      cpath: []
    }
  },
  created() {
    this.createMap()
  },
  methods: {
    createMap() {
      let that = this;
      window._AMapSecurityConfig = {
        securityJsCode: "66ebf8fc3b21d0b97694e2eba776b2fb",
      };
      that.baseMap = AMapLoader.load({
        key: "ba91a94422e9951fdd8a55fcb407aaa9", //首次调用 load 时必填
        // version: "2.0", //缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.PolyEditor", "AMap.Toolbar"], //需要使用的的插件列表
      }).then((AMap) => {
        new AMap.Map("app-container", {
          center: [116.471354, 39.994257],
          zoom: 16.8,
        });
      }).catch((e) => {
        console.log(e);
      });
    },
    createPolygon() {
      let that = this
      AMapLoader.load({
        key: "ba91a94422e9951fdd8a55fcb407aaa9", //首次调用 load 时必填
        // version: "2.0", //缺省时默认为 1.4.15
        plugins: ["AMap.PolyEditor"], //需要使用的的插件列表
      }).then((AMap) => {
        this.map = new AMap.Map("app-container", {
          zoom: 11,
          center: [116.397428, 39.90923],
        });
        // 初始化多边形
        this.polygon = new AMap.Polygon({
          path: [
            [117.397428, 39.90923],
            [116.496427, 40.80823],
            [116.397428, 39.90723],
            [117.298429, 39.70823],
          ],
          strokeColor: '#FF33FF',
          strokeOpacity: 0.2,
          strokeWeight: 3,
          fillColor: '#1791fc',
          fillOpacity: 0.35,
        });
        this.polygon.setMap(this.map);
        // 初始化多边形编辑器
        this.polyEditor = new AMap.PolyEditor(this.map, this.polygon);

        // 开启编辑模式
        this.polyEditor.open();
        // 监听编辑完成事件
        AMap.event.addListener(this.polyEditor, 'editend', () => {
          // 获取编辑后的多边形路径
          const newPath = this.polygon.getPath();
          console.log('编辑后的路径:', newPath)
          // 你可以在这里处理新的路径，比如发送到服务器
        });
        that.cpath = this.polygon.getPath()
      }).catch((e) => {
        console.error(e);
      });
    }
  }
}
</script>
<style>
#app-container {
  height: 800px;
  width: 800px;
  margin: 0;
}
</style>
